let express = require("express");
const bodyParser = require("body-parser");
const http = require("http");
// 路由
let reouter = express.Router();
// 加载模型数据库模块
let {
  broadcast_mode,
  broadcast_records,
  zhou_shan_initiator,
  sip_disposition,
  broadcast_timing_cycle,
  broadcast_timing_send,
  broadcast_cycle,
  broadcast_send,
  users,
  user_info,
} = require("../config/dbconfig");
const { Router } = require("express");
const { log } = require("console");
const { json, Op } = require("sequelize");

// 普通循环表格删除
reouter.post("/sipCycleeDel", bodyParser.json(), async (req, res, next) => {
  // 接收传输数据
  const { id } = req.body;
  const result = await broadcast_cycle.destroy({
    where: { id: JSON.parse(id) },
  });

  res.status(200).send({
    meta: {
      code: 200,
      msg: "删除成功",
    },
  });
});

//单次播放表格删除
reouter.post("/sendTableDel", bodyParser.json(), async (req, res, next) => {
  // 接收传输数据
  const { id } = req.body;
  const result = await broadcast_send.destroy({
    where: { id: JSON.parse(id) },
  });

  res.status(200).send({
    meta: {
      code: 200,
      msg: "删除成功",
    },
  });
});

//循环播放表格删除
reouter.post("/cyCleTableDel", bodyParser.json(), async (req, res, next) => {
  // 接收传输数据
  const { id } = req.body;
  const result = await broadcast_cycle.destroy({
    where: { id: JSON.parse(id) },
  });

  res.status(200).send({
    meta: {
      code: 200,
      msg: "删除成功",
    },
  });
});

//广播循环表格
reouter.post("/CycleTable", bodyParser.json(), async (req, res, next) => {
  let result; //返回结果
  const { pag, limit, call_ids } = req.body; //解析传参
  let idList = [];
  call_ids.forEach((item) => {
    idList.push({ call_id: { [Op.like]: `%${item}%` } });
  });
  let totalPages = 0; // 分页条数
  // const offset = (pag - 1) * Number(limit); // 计算偏移量
  // 没有传递最大条数
  if (limit === undefined) {
    let limitNumber = 10;
    const offset = (pag - 1) * limitNumber; // 计算偏移量
    result = await broadcast_cycle.findAndCountAll({
      limit: limitNumber, // 限制返回结果的最大数量为 pageSize
      offset: offset, // 从第 offset+1 条开始返回结果
      order: [["id", "DESC"]], // 按 id 正序排列
      where: {
        [Op.or]: idList,
      },
    });
    // 计算最大分页数量
    totalPages = Math.ceil(result.count / 10);
  } else {
    const offset = (pag - 1) * Number(limit); // 计算偏移量
    result = await broadcast_cycle.findAndCountAll({
      limit: Number(limit), // 限制返回结果的最大数量为 pageSize
      offset: offset, // 从第 offset+1 条开始返回结果
      order: [["id", "DESC"]], // 按 id 正序排列
      where: {
        [Op.or]: idList,
      },
    });
    // 计算最大分页数量
    totalPages = Math.ceil(result.count / limit);
  }
  // 放进结果
  result.total = totalPages;

  res.status(200).send({
    data: result,
  });
});

//定时发送表格
reouter.post("/timingSendTable", bodyParser.json(), async (req, res, next) => {
  let result; //返回结果
  const { pag, limit, call_ids } = req.body; //解析传参
  let idList = [];
  call_ids.forEach((item) => {
    idList.push({ call_id: { [Op.like]: `%${item}%` } });
  });
  let totalPages = 0; // 分页条数
  // const offset = (pag - 1) * Number(limit); // 计算偏移量
  // 没有传递最大条数
  if (limit === undefined) {
    let limitNumber = 10;
    const offset = (pag - 1) * limitNumber; // 计算偏移量
    result = await broadcast_timing_send.findAndCountAll({
      limit: limitNumber, // 限制返回结果的最大数量为 pageSize
      offset: offset, // 从第 offset+1 条开始返回结果
      order: [["id", "DESC"]], // 按 id 正序排列
      where: {
        [Op.or]: idList,
      },
    });
    // 计算最大分页数量
    totalPages = Math.ceil(result.count / 10);
  } else {
    const offset = (pag - 1) * Number(limit); // 计算偏移量
    result = await broadcast_timing_send.findAndCountAll({
      limit: Number(limit), // 限制返回结果的最大数量为 pageSize
      offset: offset, // 从第 offset+1 条开始返回结果
      order: [["id", "DESC"]], // 按 id 正序排列
      where: {
        [Op.or]: idList,
      },
    });
    // 计算最大分页数量
    totalPages = Math.ceil(result.count / limit);
  }
  // 放进结果
  result.total = totalPages;

  res.status(200).send({
    data: result,
  });
});

//取消和恢复定时播放
reouter.post("/timingSendQuit", bodyParser.json(), async (req, res, next) => {
  let data = req.body;
  // 更新sip服务器 端口 密码
  const result = await broadcast_timing_send.update(
    { status: data.status },
    {
      where: { id: JSON.parse(data.id) },
    }
  );

  if (result[0] === 0) {
    res.status(201).send({
      data: "修改失败,没有取消广播成功",
    });
  } else {
    // 修改成功
    res.status(200).send({
      meta: {
        code: 200,
        msg: "修改成功",
      },
    });
  }
});

// 定时发送表格删除
reouter.post("/timingSendDel", bodyParser.json(), async (req, res, next) => {
  // 接收传输数据
  const { id } = req.body;
  const result = await broadcast_timing_send.destroy({
    where: { id: JSON.parse(id) },
  });

  res.status(200).send({
    meta: {
      code: 200,
      msg: "删除成功",
    },
  });
});

// sip历史记录
reouter.post("/sipHistory", bodyParser.json(), async (req, res, next) => {
  let result; //返回结果
  let Conditions; //条件查询
  const { pag, limit, call_id } = req.body; //解析传参
  //是否有传接收地id
  if (call_id) {
    Conditions = { call_id: call_id };
  } else {
    Conditions = {};
  }
  let totalPages = 0; // 分页条数
  // const offset = (pag - 1) * Number(limit); // 计算偏移量
  // 没有传递最大条数
  if (limit === undefined) {
    let limitNumber = 10;
    const offset = (pag - 1) * limitNumber; // 计算偏移量
    result = await broadcast_records.findAndCountAll({
      limit: limitNumber, // 限制返回结果的最大数量为 pageSize
      offset: offset, // 从第 offset+1 条开始返回结果
      order: [["timestamp", "DESC"]], // 按 id 正序排列
      where: Conditions,
    });
    // 计算最大分页数量
    totalPages = Math.ceil(result.count / 10);
  } else {
    console.log(54, call_id);
    const offset = (pag - 1) * Number(limit); // 计算偏移量
    result = await broadcast_records.findAndCountAll({
      limit: Number(limit), // 限制返回结果的最大数量为 pageSize
      offset: offset, // 从第 offset+1 条开始返回结果
      order: [["timestamp", "DESC"]], // 按 id 正序排列
      where: Conditions,
    });

    // 计算最大分页数量
    totalPages = Math.ceil(result.count / limit);
  }
  // 放进结果
  result.total = totalPages;

  res.status(200).send({
    data: result,
  });
});

// sip数据更新
reouter.post("/sipUdate", bodyParser.json(), async (req, res, next) => {
  // 接收传输数据
  const data = req.body;
  // 更新数据
  let result = await broadcast_mode.update(data, {
    where: { id: JSON.parse(data.id) },
  });
  if (result[0] === 1) {
    res.status(200).send({
      data: "更新成功",
    });
  }

  if (result[0] === 0) {
    res.status(201).send({
      data: "修改失败,没有数据更新请更新数据",
    });
  }
});
// 删除
reouter.post("/sipDel", bodyParser.json(), async (req, res, next) => {
  // 接收传输数据
  const { id, activeName } = req.body;

  if (activeName === "first") {
    const result = await broadcast_timing_send.destroy({
      where: { id: JSON.parse(id) },
    });
    if (result === 1) {
      res.status(200).send({
        data: "删除成功",
      });
    }
  }

  if (activeName === "second") {
    const result = await broadcast_timing_cycle.destroy({
      where: { id: JSON.parse(id) },
    });

    console.log(178, result);

    if (result === 1) {
      res.status(200).send({
        data: "删除成功",
      });
    }
  }
  // const result = await broadcast_mode.destroy({
  //   where: { id: JSON.parse(id) },
  // });

  // if (result === 1) {
  //   res.status(200).send({
  //     data: "删除成功",
  //   });
  // }
});

//sip管理员设置服务器更新
reouter.post("/adminPut", bodyParser.json(), async (req, res, next) => {
  let data = req.body;
  // 更新sip服务器 端口 密码
  const result = await broadcast_mode.update(data, { where: {} });

  if (result[0] === 0) {
    res.status(201).send({
      data: "修改失败,没有数据更新请更新数据",
    });
  }
  // 修改成功
  res.status(200).send({
    meta: {
      code: 200,
      msg: "更新成功",
    },
  });
});

//sip发起地获取
reouter.post("/getInitiator", bodyParser.json(), async (req, res, next) => {
  let { userChanne } = req.body;
  // // 根据用户名来查询数据库是否存在这个用户
  const resUserChanne = await users.findOne({
    where: { username: userChanne },
  });

  if (resUserChanne.ChanneLlist === "all") {
    const getChanneList = await zhou_shan_initiator.findAll({ raw: true });

    res.status(200).send({
      meta: {
        code: 200,
        data: getChanneList,
      },
    });
  } else {
    let getChanneList = [];
    // 返回权限数组
    let user_Channe = resUserChanne.ChanneLlist.split(",");

    //循环查询权限
    for (const item of user_Channe) {
      const result = await zhou_shan_initiator.findOne({
        where: { id: Number(item) },
      });
      getChanneList.push(result);
    }

    res.status(200).send({
      meta: {
        code: 200,
        data: getChanneList,
      },
    });
  }
});

//sip发起地修改
reouter.post("/InitiatorPut", bodyParser.json(), async (req, res, next) => {
  let data = req.body;
  // 更新sip服务器 端口 密码
  const result = await zhou_shan_initiator.update(data, {
    where: { id: JSON.parse(data.id) },
  });
  // 修改成功
  res.status(200).send({
    meta: {
      code: 200,
      msg: "更新成功",
    },
  });
});

//sip发起地新增
reouter.post("/InitiatorAdd", bodyParser.json(), async (req, res, next) => {
  let data = req.body;
  // let initiatorData = {
  //   Initiator_id:data.Initiator_id,
  //   Initiator_name: data.Initiator_name
  // }
  const result = await zhou_shan_initiator.create(data);

  // 新增成功
  res.status(200).send({
    meta: {
      code: 200,
      msg: "新增成功",
    },
  });
});

// sip发起地删除
reouter.post("/InitiatorDel", bodyParser.json(), async (req, res, next) => {
  // 接收传输数据
  const { id } = req.body;
  const result = await zhou_shan_initiator.destroy({
    where: { id: JSON.parse(id) },
  });

  res.status(200).send({
    meta: {
      code: 200,
      msg: "删除成功",
    },
  });
});

// sip配置获取
reouter.post("/sipGet", bodyParser.json(), async (req, res, next) => {
  const result = await sip_disposition.findAll({ raw: true });

  res.status(200).send({
    meta: {
      code: 200,
    },
    data: result,
  });
});
//更新sip配置
reouter.post(
  "/sipDispositionUpdate",
  bodyParser.json(),
  async (req, res, next) => {
    let data = req.body;

    let newData = {
      registration_server: data.sip_sever,
      registration_server_port: data.port,
      password: data.password,
      user_id: data.user_id,
    };
    // 更新sip配置
    const result = await sip_disposition.update(data, { where: { id: "1" } });

    const re = await broadcast_mode.update(newData, { where: {} });

    if (result[0] === 1 && re[0] !== 0) {
      res.status(200).send({
        meta: {
          code: 200,
          msg: "更新成功",
        },
      });
    } else {
      res.status(200).send({
        meta: {
          msg: "没有更新",
        },
      });
    }
  }
);
//单次播报表格
reouter.post("/SendTable", bodyParser.json(), async (req, res, next) => {
  let result; //返回结果
  const { pag, limit, call_ids } = req.body; //解析传参
  let idList = [];
  call_ids.forEach((item) => {
    idList.push({ call_id: { [Op.like]: `%${item}%` } });
  });
  let totalPages = 0; // 分页条数
  // const offset = (pag - 1) * Number(limit); // 计算偏移量
  // 没有传递最大条数
  if (limit === undefined) {
    let limitNumber = 10;
    const offset = (pag - 1) * limitNumber; // 计算偏移量
    result = await broadcast_send.findAndCountAll({
      limit: limitNumber, // 限制返回结果的最大数量为 pageSize
      offset: offset, // 从第 offset+1 条开始返回结果
      order: [["id", "DESC"]], // 按 id 正序排列
      where: {
        [Op.or]: idList,
      },
    });
    // 计算最大分页数量
    totalPages = Math.ceil(result.count / 10);
  } else {
    const offset = (pag - 1) * Number(limit); // 计算偏移量
    result = await broadcast_send.findAndCountAll({
      limit: Number(limit), // 限制返回结果的最大数量为 pageSize
      offset: offset, // 从第 offset+1 条开始返回结果
      order: [["id", "DESC"]], // 按 id 正序排列
      where: { call_id: { [Op.in]: "1046" } },
    });
    // 计算最大分页数量
    totalPages = Math.ceil(result.count / limit);
  }
  // 放进结果
  result.total = totalPages;

  res.status(200).send({
    data: result,
  });
});

//sip用户表
reouter.post("/sipUser", bodyParser.json(), async (req, res, next) => {
  let result = await user_info.findAndCountAll({
    raw: true,
  });

  res.status(200).send({
    data: result,
  });
});

module.exports = reouter;
